package com.zxx.coolweather._wuguan3_ok;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;
import okio.GzipSink;
import okio.Okio;

/**
 * OkHttp3是支持Gzip解压缩的
 * 在向服务器提交大量数据的时候，希望对post的数据进行gzip压缩
 *
 * 在发起请求的时候自动加入header，Accept-Encoding: gzip.
 * 服务器返回的时候header中有Content-Encoding: gzip.
 *
 * @author zxx on 2022/1/19
 */
public class GzipRequestInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originRequest = chain.request();
        if (originRequest.body() == null || originRequest.header("Content-Encoding") != null) {
            return chain.proceed(originRequest);
        }

        Request compressRequest = originRequest.newBuilder()
                .header("Content-Encoding", "gzip")
                .method(originRequest.method(), gzip(originRequest.body()))
                .build();

        return chain.proceed(compressRequest);
    }

    private RequestBody gzip(final RequestBody body) {
        return new RequestBody() {
            @Override
            public MediaType contentType() {
                return body.contentType();
            }

            @Override
            public long contentLength() throws IOException {
                return -1;  // 无法提前知道压缩后的数据大小
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
                body.writeTo(gzipSink);
                gzipSink.close();
            }
        };
    }
}
